﻿package rd.hardcore.selector 
{
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import hype.extended.behavior.MouseFollow;
	/**
	 * ...
	 * @author Thibault Perret
	 */
	public class ScrollBar extends Sprite
	{
		/*	V A R 	*/
		public var bg:Sprite;
		public var cursor:Sprite;
		
		
		private var ratio:Number;
		private var sp:Sprite = new Sprite();
		
		
		/*	P U B L I C	*/
		public function ScrollBar() 
		{
			cursor.buttonMode = true;
			cursor.addEventListener(MouseEvent.MOUSE_OVER, handleOver);
			cursor.addEventListener(MouseEvent.MOUSE_OUT, handleOut);
			
			cursor.addEventListener(MouseEvent.MOUSE_DOWN, handleDown);
			addEventListener(MouseEvent.MOUSE_UP, handleUp);
			
			cursor.addEventListener(MouseEvent.MOUSE_WHEEL, onWheelUse);
			bg.addEventListener(MouseEvent.MOUSE_WHEEL, onWheelUse);
			
		}
		
		public function setCursor(_ratio:Number):void {
			ratio = _ratio;
			cursor.y = ratio * (bg.height -40) +1;
		}
		
		/**
		 * Masque la scrollBar et la rend inactive
		 */
		public function hide():void {
			cursor.alpha = 0;
			bg.alpha = 0;
			mouseEnabled = false;
		}
		
		/**
		 * Rend visible et active la scrollBar
		 */
		public function show():void {
			cursor.alpha = 1;
			bg.alpha = 1;
			mouseEnabled = true;
		}
		
		/*	P R I V A T E 	*/
		private function onWheelUse(e:MouseEvent):void 
		{
			cursor.y += - 3*e.delta;
			if (cursor.y < 1)	cursor.y = 1;
			if (cursor.y > bg.height - 39)	cursor.y = bg.height -39;
			ratio = (cursor.y -1) / (bg.height - 40);
			dispatchEvent(new ScrollEvent(ScrollEvent.BAR_SCROLLING, ratio, true));
		}
		
		private function handleUp(e:MouseEvent):void 
		{
			cursor.stopDrag();
			removeEventListener(Event.ENTER_FRAME, handleFrame);
		}
		
		private function handleDown(e:MouseEvent):void 
		{
			
			cursor.startDrag(false, new Rectangle(0, 1, 0, bg.height - 40));
			addEventListener(Event.ENTER_FRAME, handleFrame);
		}
		
		private function handleOut(e:MouseEvent):void 
		{
			cursor.stopDrag();
			removeEventListener(Event.ENTER_FRAME, handleFrame);
			cursor.alpha = 1;
		}
		private function handleOver(e:MouseEvent):void 
		{
			cursor.alpha = .8;
		}
		private function handleFrame(e:Event):void 
		{
			ratio = (cursor.y -1) / (bg.height - 40);
			dispatchEvent(new ScrollEvent(ScrollEvent.BAR_SCROLLING, ratio, true));
		}
		
		
		
	}

}